<template>
  <div class="page-container">
    <div class="quick-search">
      <div
        v-for="item in quickSearchData"
        :key="item.key"
        class="quick-search-item"
        :class="[item.checked ? 'quick-search-item-checked' : '']"
        @click="quickSearchClick(item)"
      >
        <div class="quick-search-item-label">{{ item.label }}</div>
        <div class="quick-search-item-value" :class="[item.checked ? 'quick-search-item-value-checked' : '']">{{ item.value }}</div>
      </div>
    </div>
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="initLoadData" @reset="searcherReset" />
    <div class="table-summary-box">
      <div class="table-info">
        <span class="table-info-item"> 已发送的签署短信：{{ headerConfig != null ? headerConfig + '条' : '-' }}</span>
      </div>
      <a-alert title="普通版电子合同费用说明：">
        <template #icon>
          <icon-exclamation-circle />
        </template>
        <div>1. 【发送签署短信】会将签署链接以短信的形式发送给承租方的手机号，商户需承担短信费用</div>
      </a-alert>
    </div>
    <table-index :table="table" @loadData="loadData">
      <template #orderCode="{ record }">
        <template v-if="record.orderCode">
          <a-link type="link" @click="() => onLink(record)" style="color: rgba(24, 144, 255, 1); text-decoration: underline">
            {{ record.orderCode }}
          </a-link>
        </template>
        <div v-else>-</div>
      </template>

      <template #lesseeName="{ record }">
        <div v-if="record.leaseType === 2">{{ record.lesseeName || '-' }}</div>
        <div v-else>
          <div>{{ record.lesseeCompanyName || '-' }}</div>
        </div>
      </template>

      <template #contractStatus="{ record }">
        <div class="status" :class="getClassName(record)">{{ record.contractStatusName }}</div>
        <a-button type="primary" size="mini" v-if="record.contractStatus == -1" @click="errorShow(record)">原因</a-button>
        <div v-if="record.contractStatus == 2 || record.contractStatus == 3 || record.contractStatus == 8">
          承租方：
          <!-- 签署中 -->
          <span class="block" v-if="record.contractStatus == 2" :class="record.lesseeSignStatus === 1 ? 'block-unsign' : 'block-signed'">
            {{ record.lesseeSignStatusName }}
          </span>
          <!-- 已作废 -->
          <span
            class="block"
            v-if="record.contractStatus == 8"
            :class="record.lesseeInvalidedStatus === 1 ? 'block-unsign' : 'block-signed'"
          >
            {{ record.lesseeInvalidedStatusName }}
          </span>
          <!-- 已完成 -->
          <span class="block" v-if="record.contractStatus == 3" :class="record.lesseeSignStatus === 1 ? 'block-unsign' : 'block-signed'">
            {{ record.lesseeSignStatusName }}
          </span>

          <a-button
            type="text"
            size="mini"
            @click="onCopy(record, '已将链接复制到剪切板')"
            v-permission="'svms:business:contract:sign.contractCopySigningLink'"
          >
            <template #icon>
              <icon-link />
            </template>
            复制合同链接
          </a-button>
        </div>
        <div v-if="record.contractStatus == 2 || record.contractStatus == 3 || record.contractStatus == 8">
          出租方：
          <span class="block" v-if="record.contractStatus === 2" :class="record.hireSignStatus === 1 ? 'block-unsign' : 'block-signed'">
            {{ record.hireSignStatusName }}
          </span>
          <span
            class="block"
            v-if="record.contractStatus === 8"
            :class="record.hireInvalidedStatus === 1 ? 'block-unsign' : 'block-signed'"
          >
            {{ record.hireInvalidedStatusName }}
          </span>
          <span class="block" v-if="record.contractStatus == 3" :class="record.lesseeSignStatus === 1 ? 'block-unsign' : 'block-signed'">
            {{ record.lesseeSignStatusName }}
          </span>
        </div>
      </template>
    </table-index>
  </div>
  <!-- 生成电子合同 -->
  <ViewContractModal v-model:visible="viewVisible" v-model:loading="viewLoading" :order="viewContractInfo" @on-ok="onOkContract" />
  <!-- 预览pdf -->
  <pdf-viewer
    :url="pdfViewInfo.url"
    :title="pdfViewInfo.title"
    v-model:visible="pdfViewInfo.show"
    @close="Object.assign(pdfViewInfo, { ...PDFDefaultAttr })"
  />
</template>

<script setup lang="ts">
  import { ref, computed, reactive, onMounted } from 'vue'
  import ViewContractModal from '@/views/order/modals/view-contract-modal.vue'

  import { useExport } from '@/hooks/list'
  import { useFetchTableDataApi, useTable } from '@/hooks/table'
  import useClipboard from 'vue-clipboard3'
  import { Message, Modal } from '@arco-design/web-vue'
  import {
    getContractSignRecord,
    getContractTenantSignUrl,
    exportContractAuthRecord,
    getMsgNumCount,
    contractSignRecordCount,
    sendLesseeSignMsg,
  } from '@/api/business/contract'
  import { getContractInfo, updateFreeContract } from '@/api/order/sOrder'
  import { usePageDict } from '@/hooks/useDict'
  import request from '@/api/axios.config'
  import { revokeAPI, nullifyAPI } from '@/api/order/sOrder'
  import useNavigate from '@/hooks/useNavigate'
  import useUserStore from '@/store/modules/user'

  // pdf预览
  import { PDFDefaultAttr } from '@/components/pdf-viewer/const'
  const pdfViewInfo = reactive({ ...PDFDefaultAttr })

  const userStore = useUserStore() as any
  userStore.setEpDetail()
  const pageDict = usePageDict('systemParamDict')
  console.log(pageDict, 'pageDict')
  console.log(userStore, 'userStore')

  const viewVisible = ref(false)
  const viewLoading = ref(false)
  const viewContractInfo = ref()

  const { navigateTo } = useNavigate()

  const { toClipboard } = useClipboard()
  const quickSearchData = ref([
    {
      key: 2,
      label: '签署中合同数(份)',
      value: 0,
      checked: false,
    },
    {
      key: 3,
      label: '已完成合同数(份)',
      value: 0,
      checked: false,
    },
    {
      key: 5,
      label: '已撤回合同数(份)',
      value: 0,
      checked: false,
    },
    {
      key: 8,
      label: '已作废合同数(份)',
      value: 0,
      checked: false,
    },
  ])

  const quickSearchClick = (item: any) => {
    quickSearchData.value.forEach((i: any) => {
      i.checked = false
    })
    item.checked = true
    queryParam.contractStatusList = [item.key]
    loadData(1)
    getMsgNumCountFn()
  }

  const getClassName = (record: any) => {
    switch (record.contractStatus) {
      case 1:
        return 'status-unauth'
      case 2:
        return 'status-signing'
      case 3:
      case 10:
        return 'status-success'
      case 4:
      case 5:
      case -1:
      case 6:
      case 8:
      case 11:
        return 'status-finish'
      case 7:
        return 'status-failed'
      case 9:
        return 'status-invalid'
    }
  }

  const queryParam = reactive<any>({
    createTimeRange: [],
    dateRange: [],
    payType: 0,
  })
  const searchList = computed(() => {
    return [
      { label: '合同编号', prop: 'contractNo', type: 'a-input', maxlength: 30 },
      { label: '关联订单编号', prop: 'orderCode', type: 'a-input', maxlength: 30 },
      { label: '客户名称', prop: 'lesseeName', type: 'a-input' },
      {
        label: '合同状态',
        prop: 'contractStatusList',
        type: 'a-select',
        options:
          pageDict.contractStatus &&
          pageDict.contractStatus.filter((item: any) => {
            if (item.value === 2 || item.value === 3 || item.value === 8 || item.value === 5) {
              return {
                label: item.label,
                value: item.value,
              }
            }
          }),
        attrs: {
          multiple: true,
        },
      },
      {
        label: '业务类型',
        prop: 'orderType',
        type: 'a-select',
        options: pageDict.orderType,
      },
      {
        label: '合同服务类型',
        prop: 'contractTypeList',
        type: 'a-select',
        options: pageDict.freeContractType,
        attrs: {
          multiple: true,
        },
      },
      {
        label: '客户类型',
        prop: 'leaseType',
        type: 'a-select',
        options: pageDict.leaseType,
      },
      {
        label: '所属门店',
        prop: 'siteList',
        type: 'remote-select',
        attrs: {
          multiple: true,
          type: 'multiple_site_listBystaff',
        },
      },
      {
        label: '生成合同时间',
        prop: 'createTimeRange',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:23:59'],
          },
        },
        change: (value = []) => {
          queryParam.startTimeStart = value[0]
          queryParam.startTimeEnd = value[1]
        },
      },
      {
        label: '完成签署时间',
        prop: 'dateRange',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:23:59'],
          },
        },
        change: (value = []) => {
          queryParam.completeTimeStart = value[0]
          queryParam.completeTimeEnd = value[1]
        },
      },
      {
        label: '发起人',
        prop: 'startPersonIdList',
        type: 'remote-select',
        attrs: {
          mode: 'multiple',
          type: 'sync_staff_multiple_likeRealname',
        },
      },
    ]
  })

  const table = useTable({
    columns: [
      {
        title: '合同编号',
        dataIndex: 'contractNo',
        width: 200,
        fixed: 'left',
      },
      {
        title: '关联单号',
        dataIndex: 'orderCode',
        slotName: 'orderCode',
        width: 220,
      },
      {
        title: '归属门店',
        dataIndex: 'siteName',
        width: 150,
      },
      {
        title: '业务类型',
        dataIndex: 'orderTypeName',
        width: 100,
      },
      {
        title: '合同类型',
        dataIndex: 'contractTypeName',
        width: 100,
      },
      {
        title: '合同模板名称',
        dataIndex: 'templateName',
        width: 220,
      },
      {
        title: '合同状态',
        dataIndex: 'contractStatus',
        slotName: 'contractStatus',
        width: 260,
      },
      {
        title: '客户类型',
        dataIndex: 'leaseTypeName',
        width: 100,
      },
      {
        title: '客户信息',
        dataIndex: 'lesseeName',
        slotName: 'lesseeName',
        width: 100,
      },
      {
        title: '签署短信条数',
        dataIndex: 'msgNum',
        titleTooltipContent: '发送签署链接的短信会单独收费',
        width: 130,
      },
      {
        title: '发起节点',
        dataIndex: 'startNode',
        width: 100,
      },
      {
        title: '生成合同时间',
        dataIndex: 'createTime',
        width: 170,
      },
      {
        title: '完成签署时间',
        dataIndex: 'completeTime',
        width: 170,
      },
      {
        title: '发起人',
        dataIndex: 'startPersonName',
        width: 100,
      },
    ],
    operates: [
      {
        label: '预览',
        permission: 'svms:business:contract:sign.preview',
        method: (record: any) => {
          request
            .post(
              '/svmsContract/downloadContractFile',
              {
                id: record.id,
              },
              {
                responseType: 'blob',
              }
            )
            .then((res) => {
              console.log(res)
              const binaryData = []
              binaryData.push(res.data)
              let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }))
              window.open(url)
              // Object.assign(pdfViewInfo, {
              //   url,
              //   title: record.contractTypeName + record.contractNo,
              //   show: true,
              // })
            })
        },
      },
      {
        label: '发送签署短信',
        permission: 'svms:business:contract:sign.message',
        show: (record: any) => record.contractStatus == 2,
        method: (record: any) => {
          console.log(record)
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            content: `发送签署短信会产生短信费用，请确认是否发送？`,
            onOk: () => {
              sendLesseeSignMsg({ id: record.id }).then((res: any) => {
                console.log(res)
                Message.success('已将合同签署链接发送至当前合同的承租人手机号')
                init()
              })
            },
          })
        },
      },
      // 修改合同
      {
        label: '修改合同',
        permission: 'svms:business:contract:sign.contractModify',
        show: (record: any) => record.contractStatus == 2,
        method: (record: any) => {
          getContractInfo({ id: record.id, orderType: record.orderType, contractType: record.contractType }).then((res: any) => {
            res.result.contractFee.forEach((item: any) => {
              item.value = +item.value
            })

            viewContractInfo.value = {
              ...res.result,
              contractType: record.contractType,
              contractId: record.id,
              timeRange: [res.result.startTime, res.result.endTime],
              sendServiceFlag: res.result.sendServiceFlag == 1 ? true : false,
              returnServiceFlag: res.result.returnServiceFlag == 1 ? true : false,
              method: 'update',
            }

            console.log('修改合同', res, viewContractInfo.value)
            viewVisible.value = true
          })
        },
      },
      {
        label: '撤回',
        permission: 'svms:business:contract:sign.revoke',
        show: (record: any) => record.contractStatus === 2,
        method: (record: any) => {
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            content: `合同撤回后，承租方签署链接失效，无法完成签署，确认撤回吗？`,
            onOk: () => {
              revokeAPI({ id: record.id }).then(() => {
                Message.success('操作成功')
                init()
              })
            },
          })
        },
      },
      {
        label: '作废',
        permission: 'svms:business:contract:sign.nullify',
        show: (record: any) => record.contractStatus === 3,
        method: (record: any) => {
          console.log(record)
          nullifyFn(record)
        },
      },
      {
        label: '下载',
        permission: 'svms:business:contract:sign.download',
        show: (record: any) => record.contractStatus === 3 || record.contractStatus === 8,
        method: (record: any) => {
          console.log(record)
          request
            .post(
              '/svmsContract/downloadContractFile',
              {
                id: record.id,
              },
              {
                responseType: 'blob',
              }
            )
            .then((res) => {
              console.log(res)
              fileDownload(res.data, record)
            })
        },
      },
    ],
    buttons: [
      {
        mode: 'export',
        permission: 'svms:business:contract:sign.export',
        label: '导出',
        method: () => handleExport(),
      },
    ],
  })

  // 导出事件
  const handleExport = () => {
    useExport(exportContractAuthRecord, queryParam)
  }

  // 列表里点击失败原因
  const errorShow = (record: any) => {
    if (record.createErrorCode == 1001) {
      // 1. 姓名手机号不匹配时
      toError(record)
    } else {
      // 2. 其他原因（没有前往修改按钮）
      Modal.confirm({
        title: '提示',
        simple: true,
        hideCancel: true,
        okText: '关闭',
        content: record.createErrorReason,
      })
    }
  }

  // 去修改订单
  const toError = (record: any) => {
    Modal.confirm({
      title: '合同生成失败',
      simple: true,
      cancelText: '关闭',
      okText: '前往修改',
      content: '请将承租人姓名修改为上次已通过实名认证的姓名，再进行重新生成合同的操作。',
      onOk: () => {
        if (record.orderType === 1) {
          navigateTo(`/short-order/edit/${record.orderId}`, `${record.orderCode}-修改订单`)
        } else {
          navigateTo(`/long-order/edit/${record.orderId}`, `${record.orderCode}-修改订单`)
        }
      },
    })
  }

  // 作废
  const nullifyFn = (record: any) => {
    Modal.confirm({
      title: '提示',
      simple: true,
      cancelText: '取消',
      okText: '确认',
      content: `合同已完成签署，确认作废吗?`,
      onOk: () => {
        // 发起作废接口
        nullifyAPI({ id: record.id }).then((res: any) => {
          console.log(res)
          if (res.code == 200) {
            init()
          }
        })
      },
    })
  }

  const onLink = (record: any) => {
    if (record.orderType == 1) {
      navigateTo(`/short-order/detail/${record.orderId}`, `${record.orderCode}-短租详情`)
    } else if (record.orderType == 2) {
      navigateTo(`/long-order/detail/${record.orderId}`, `${record.orderCode}-长租详情`)
    }
  }

  // 文件下载
  const fileDownload = (_res: any, record: any) => {
    let blob = new Blob([_res], { type: 'application/pdf' })
    let downloadElement = document.createElement('a')
    let href = window.URL.createObjectURL(blob) //创建下载的链接
    downloadElement.href = href
    // downloadElement.download = fileName; //下载后文件名
    downloadElement.download = record.contractTypeName + record.contractNo //下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() //点击下载
    document.body.removeChild(downloadElement) //下载完成移除元素
    window.URL.revokeObjectURL(href) //释放掉blob对象
  }

  const onCopy = (record: any, message?: any) => {
    getContractTenantSignUrl({ id: record.id }).then((res: any) => {
      copy(res.result, message)
    })
  }

  const headerConfig = ref()
  // 获取签署记录表头统计
  const getMsgNumCountFn = () => {
    getMsgNumCount(queryParam).then((res: any) => {
      headerConfig.value = res.result
    })
  }

  // 签署记录统计
  const getContractSignRecordCount = () => {
    contractSignRecordCount(queryParam).then((res) => {
      console.log(res, 'res')
      const result = res.result
      result.forEach((item: any) => {
        quickSearchData.value.forEach((i: any) => {
          if (i.key == item.contractStatus) {
            i.value = item.contractCount
          }
        })
      })
    })
  }

  const searcherReset = () => {
    quickSearchData.value.forEach((i: any) => {
      i.checked = false
    })
  }

  const loadData = useFetchTableDataApi(table, queryParam, getContractSignRecord)

  // 修改合同
  const onOkContract = (options: any) => {
    viewLoading.value = true

    const { detail } = options

    console.log('detail', detail)
    if (detail.contractId) {
      updateFreeContract({ ...detail, id: detail.contractId }).then((res: any) => {
        console.log('updateFreeContract', res)
        viewVisible.value = false
        viewLoading.value = false
        init()
      })
    }
  }
  const init = () => {
    loadData()
    getMsgNumCountFn()
    getContractSignRecordCount()
  }
  const initLoadData = () => {
    loadData()
    getMsgNumCountFn()
  }

  onMounted(() => {
    init()
  })

  /**
   * 复制
   * @param value 复制的值
   */
  const copy = async (value: any, message = '复制成功') => {
    try {
      await toClipboard(value)
      Message.success(message)
    } catch (error) {
      Message.error('复制失败')
    }
  }
</script>

<style lang="less" scoped>
  .service-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 500px;

    &-img {
      width: 86px;
      height: 129px;
      margin-bottom: 27px;
    }

    &-text {
      font-size: 16px;
      font-weight: 400;
      color: #1d2129;
    }
  }

  .page-container {
    padding-top: 0;
    .quick-search {
      display: flex;
      margin-bottom: 20px;

      &-item {
        width: 16%;
        height: 62px;
        padding: 9px 0 9px 16px;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #e5e8ef;
        cursor: pointer;

        &:hover {
          transform: scale(1.1);
          transition: transform 0.3s;
          position: relative;
          z-index: 999;
        }

        &-checked {
          background: #e8f3ff;
          border-radius: 4px 4px 4px 4px;
          border: 1px solid #1890ff;
        }

        &:nth-of-type(n + 2) {
          margin-left: 20px;
        }

        &-label {
          font-size: 12px;
          font-weight: 400;
          color: #4e5969;
        }

        &-value {
          font-size: 20px;
          font-weight: 600;
          color: #1d2129;

          &-checked {
            color: #1890ff;
          }
        }
      }
    }

    .table-summary-box {
      padding: 20px 20px;
      margin-bottom: 20px;
      background: #f7f8fa;

      .table-info {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        &-item {
          margin-right: 20px;
          span {
            color: #1890ff;
          }
        }
      }
    }

    .status {
      font-size: 14px;
      font-weight: 400;
      color: rgba(185, 187, 196, 1);

      &.status-unauth {
        color: rgba(185, 187, 196, 1);
      }
      &.status-signing {
        color: rgba(52, 145, 250, 1);
      }
      &.status-success {
        color: rgba(0, 180, 42, 1);
      }
      &.status-finish {
        color: rgba(245, 63, 63, 1);
      }

      &.status-failed {
        color: rgba(255, 125, 0, 1);
      }
      &.status-invalid {
        color: rgba(114, 46, 209, 1);
      }
    }

    .block {
      display: inline-flex;
      justify-content: center;
      align-items: center;
      height: 20px;
      padding: 0 8px;
      font-size: 12px;
      font-weight: 500;
      border-radius: 2px 2px 2px 2px;
      border: 1px solid;

      &.block-unsign {
        color: rgba(255, 125, 0, 1);
        border-color: rgba(255, 125, 0, 1);
        background-color: rgba(255, 247, 232, 1);
      }

      &.block-signed {
        color: rgba(0, 180, 42, 1);
        border-color: rgba(0, 180, 42, 1);
        background-color: rgba(232, 255, 234, 1);
      }
    }
  }
</style>
